<?php

/**
 * Created by PhpStorm.
 * Author: ls
 * Time: 2023/12/11 9:25
 * Desc: 门票sku
 */
class Model_Spot_Ticket_Sku extends ORM
{

    protected $_table_name = 'spot_ticket_sku';


    /**
     * 通过分时预约时段删除规格
     * @param array $period_time_id
     * @return void
     */
    public static function del_by_period_time(array $period_time_id)
    {
        // 查询要删除的sku
        $sku_ids = DB::select()
            ->from('spot_ticket_sku')
            ->where('period_time_id', 'in', $period_time_id)
            ->execute()
            ->as_array('id', 'id');
        if (!empty($sku_ids)) {
            DB::delete('spot_ticket_sku')->where('id', 'in', $sku_ids)->execute();

            // 删除相关报价
            Model_Spot_Ticket_Price::del_by_sku($sku_ids);
        }
    }

    /**
     * 通过景点id删除规格
     * @param array $spot_id
     * @return void
     */
    public static function del_by_spot_id($spot_id)
    {
        // 查询要删除的sku
        $sku_ids = DB::select()
            ->from('spot_ticket_sku')
            ->where('spot_id', '=', $spot_id)
            ->execute()
            ->as_array('id', 'id');
        if (!empty($sku_ids)) {
            DB::delete('spot_ticket_sku')->where('id', 'in', $sku_ids)->execute();

            // 删除相关报价
            Model_Spot_Ticket_Price::del_by_sku($sku_ids);
        }
    }

    /**
     * 创建sku数据
     * @param $spot_id
     * @param $sku_item_id
     * @param string $sku_item_type ticket|period_time|other_attr
     * @return array
     */
    public static function make_sku_data($spot_id, $sku_item_id, $sku_item_type)
    {

        switch ($sku_item_type) {
            case 'ticket':
                $sku_item_key = 'ticket_id';
                break;
            default:
                $sku_item_key = 'period_time_id';
                break;
        }

        $data = array();
        if ($sku_item_type != 'ticket') {
            $ticket_ids = DB::select()
                ->from('spot_ticket')
                ->where('spotid', '=', $spot_id)
                ->execute()
                ->as_array('id', 'id');
            // 格式化时间
            if (!empty($ticket_ids)) {
                $data['ticket_id'] = [];
                foreach ($ticket_ids as $ticket_id) {
                    $data['ticket_id'][] = $ticket_id;
                }
            }
        }

        if ($sku_item_type != 'period_time') {
            $period_times = DB::select()
                ->from('spot_ticket_period_time')
                ->where('spot_id', '=', $spot_id)
                ->execute()
                ->as_array('id', 'period_time_id');

            if (!empty($period_times)) {
                $data['period_time_id'] = [];
                foreach ($period_times as $period_time) {
                    $data['period_time_id'][] = $period_time;
                }
            }
        }

        $base_data = array(
            $sku_item_key => $sku_item_id,
            'spot_id' => $spot_id,
            'addtime' => time()
        );

        $new_data = array();
        if (!empty($data)) {
            foreach ($data as $key => $item) {
                $new_data = self::create_sku_data($new_data, $key, $item);
            }

            // 合并基础数据
            foreach ($new_data as &$new_item) {
                $new_item = array_merge($new_item, $base_data);
            }
        }

        return $new_data;
    }

    /**
     * 创建规格数据
     * @param $base_data
     * @param $key
     * @param $item
     * @return array
     */
    public static function create_sku_data($base_data, $key, $item)
    {
        if (!empty($base_data)) {
            foreach ($base_data as $base_item) {
                foreach ($item as $value) {
                    $base_item[$key] = $value;
                }
            }
        } else {
            foreach ($item as $v) {
                $base_data[][$key] = $v;
            }
        }
        return $base_data;
    }

    /**
     * @param $spot_id
     * @param $sku_item_id
     * @param string $sku_item_type ticket|period_time|other_attr
     * @return true
     * @throws Kohana_Exception
     */
    public static function add_sku($spot_id, $sku_item_id, $sku_item_type)
    {
        $data = self::make_sku_data($spot_id, $sku_item_id, $sku_item_type);

        if (!empty($data)) {
            foreach ($data as $item) {
                $builder = DB::select()
                    ->from('spot_ticket_sku');
                foreach ($item as $k => $v) {
                    $builder->where($k, '=', $v);
                }
                $sku = $builder->execute()->valid();
                if (!$sku) {
                    DB::insert('spot_ticket_sku', array_keys($item))->values(array_values($item))->execute();
                }
            }
        }
        return true;
    }

    /**
     * 切换时段关闭
     * @param $spot_id
     * @param string $period_time_id 为空时关闭全部时段
     * @return void
     */
    public static function close_period_time($spot_id, string $period_time_id = '')
    {
        $builder = DB::select()
            ->from('spot_ticket_sku')
            ->where('spot_id', '=', $spot_id);
        if ($period_time_id) {
            $builder->where('period_time_id', '=', $period_time_id);
        } else {
            $builder->where('period_time_id', '>', 0);
        }
        $sku_ids = $builder->execute()
            ->as_array('id', 'id');

        // 删除门票关联的时段
        $period_time_ids = $period_time_id ? array($period_time_id) : array();
        Model_Spot_Ticket_Period_Time::del_by_period_time($period_time_ids, $spot_id);

        if (!empty($sku_ids)) {
            self::delete_clear($sku_ids);
        }
    }

    /**
     * 规格删除清理
     * @param $sku_ids
     * @return void
     */
    public static function delete_clear($sku_ids)
    {
        // 删除价格
        DB::delete('spot_ticket_price')
            ->where('sku_id', 'in', $sku_ids)
            ->execute();

        // 删除规格
        DB::delete('spot_ticket_sku')
            ->where('id', 'in', $sku_ids)
            ->execute();
    }


    /**
     * 切换景区规格通过时段
     * @param $spot_id
     * @param $period_time_id
     * @param int $is_checked 1 添加 0 删除
     * @return true
     * @throws Kohana_Exception
     */
    public static function change_sku_period_time($spot_id, $period_time_id, $is_checked)
    {
        if ($is_checked == 1) {
            // 添加套餐规格
            self::add_sku($spot_id, $period_time_id, 'period_time');
            // 添加景区时段关联
            Model_Spot_Ticket_Period_Time::save_period_time($period_time_id, $spot_id);
        } else {
            // 删除相关规格
            self::close_period_time($spot_id, $period_time_id);
        }
        return true;
    }

    /**
     * 保存门票规格中分时时段
     * @param $spot_id
     * @param $ticket_id
     * @param array $period_time_ids
     * @return void
     * @throws Kohana_Exception
     */
    public static function save_ticket_sku_period_time($spot_id, $ticket_id, array $period_time_ids)
    {
        //需要处理的数据
        $period_time_arr = array();

        // 原始数据
        $ticket_period_time_list = Model_Spot_Ticket::get_ticket_period_time($spot_id, $ticket_id);
        $ticket_period_time_list = !empty($ticket_period_time_list) ? Arr::pluck($ticket_period_time_list, 'period_time_id') : array();
        // 添加的数据
        foreach ($period_time_ids as $item) {
            if (!in_array($item, $ticket_period_time_list)) {
                $period_time_arr[] = array(
                    'type' => 1,
                    'id' => $item
                );
            }
        }

        // 删除的数据
        foreach ($ticket_period_time_list as $ticket_period_time_id) {
            if (!in_array($ticket_period_time_id, $period_time_ids)) {
                $period_time_arr[] = array(
                    'type' => 0,
                    'id' => $ticket_period_time_id
                );
            }
        }

        foreach ($period_time_arr as $period_time) {
            Model_Spot_Ticket_Sku::change_ticket_sku_period_time($spot_id, $ticket_id, $period_time['id'], $period_time['type']);
        }
    }

    /**
     * 使用或关闭门票规格中的场次
     * @param $spot_id
     * @param $ticket_id
     * @param $period_time_id
     * @param $is_checked
     * @return true
     * @throws Kohana_Exception
     */
    public static function change_ticket_sku_period_time($spot_id, $ticket_id, $period_time_id, $is_checked)
    {
        if ($is_checked == 1) {
            // 添加
            $data = array(
                'period_time_id' => $period_time_id,
                'spot_id' => $spot_id,
                'ticket_id' => $ticket_id,
                'addtime' => time()
            );
            DB::insert('spot_ticket_sku', array_keys($data))->values(array_values($data))->execute();
        } else {
            // 删除
            $sku_ids = DB::select()
                ->from('spot_ticket_sku')
                ->where('ticket_id', '=', $ticket_id)
                ->where('period_time_id', '=', $period_time_id)
                ->execute()
                ->as_array('id', 'id');

            if (!empty($sku_ids)) {
                self::delete_clear($sku_ids);
            }
        }
        return true;
    }

    /**
     * 创建sku Title
     * @param $sku
     * @param $ticket_title
     * @return string
     */
    public static function make_title($sku, $ticket_title)
    {
        $title = '';

        $period_time = DB::select('start', 'end')
            ->from('spot_period_time')
            ->where('id', '=', $sku['period_time_id'])
            ->execute()
            ->current();
        if ($period_time) {
            $title .= $period_time['start'] . '-' . $period_time['end'];
        }

        if ($ticket_title) {
            $title = $ticket_title . ' ' . $title;
        }

        return $title;
    }

    /**
     * 按报价获取门票规格
     * @param $spot_id
     * @param array $params ticket_id; $sku_id = [ 'ticket_id' => ['sku_id', 'sku_id'] ]
     * @return array
     */
    public static function get_price_sku($spot_id, $params = array())
    {
        $ticket_id = Arr::get($params, 'ticket_id', '');
        $sku_id    = Arr::get($params, 'sku_id', '');
        $status    = Arr::get($params, 'status', '');
        // 查询已维护的套餐
        $builder = DB::select('id', 'title', 'settlement_type', 'sellprice', 'fill_tourer_type')
            ->from('spot_ticket')
            ->where('spotid', '=', $spot_id)
            ->and_where('is_edited', '=', 1);
        if (!empty($ticket_id)) {
            if (is_array($ticket_id)) {
                $builder->and_where('id', 'in', $ticket_id);
            } else {
                $builder->and_where('id', '=', $ticket_id);
            }
        }
        if (!empty($status)) {
            $builder->and_where('status', '=', $status);
        }else{
            $builder->and_where('status', '!=', 0);
        }
        $tickets = $builder->order_by('settlement_type', 'asc')->execute()->as_array();

        $skus = array();
        if (!empty($tickets)) {
            foreach ($tickets as $ticket) {
                $ticket_sku = self::make_ticket_sku($spot_id, $ticket);
                $skus       = array_merge($skus, $ticket_sku);
            }
        }

        // 筛选
        if (!empty($skus) && !empty($sku_id)) {
            foreach ($skus as $key => $sku) {
                if (isset($sku_id[$sku['ticket_id']])) {
                    if (!in_array($sku['sku_id'], $sku_id[$sku['ticket_id']])) {
                        unset($skus[$key]);
                    }
                } else {
                    unset($skus[$key]);
                }
            }
        }

        return $skus ? array_values($skus) : array();
    }


    /**
     * 生成门票规格
     * @param $spot_id
     * @param $ticket
     * @return array
     */
    public static function make_ticket_sku($spot_id, $ticket)
    {
        $prices = array();
        // 查询门票是否有规格
        $skus = DB::select()
            ->from('spot_ticket_sku')
            ->where('ticket_id', '=', $ticket['id'])
            ->and_where('spot_id', '=', $spot_id)
            ->execute()
            ->as_array();
        if (!empty($skus)) {
            foreach ($skus as $sku) {
                $prices[] = array(
                    'ticket_id' => $ticket['id'],
                    'sku_id' => $sku['id'],
                    'period_time_id' => $sku['period_time_id'],
                    'title' => Model_Spot_Ticket_Sku::make_title($sku, $ticket['title']),
                    'tag' => $ticket['id'] . '-' . $sku['id'],
                    'settlement_type' => $ticket['settlement_type'],
                    'sellprice' => $ticket['sellprice'],
                    'fill_tourer_type' => $ticket['fill_tourer_type'],
                );
            }
        } else {
            $prices[] = array(
                'ticket_id' => $ticket['id'],
                'sku_id' => 0,
                'period_time_id' => 0,
                'title' => $ticket['title'],
                'tag' => $ticket['id'] . '-0',
                'settlement_type' => $ticket['settlement_type'],
                'sellprice' => $ticket['sellprice'],
                'fill_tourer_type' => $ticket['fill_tourer_type'],
            );
        }

        return $prices;
    }

    /**
     * 获取规格信息
     * @param $sku_id
     * @return array|false|mixed
     */
    public static function get_sku_info($sku_id)
    {
        $sku = DB::select()
            ->from('spot_ticket_sku')
            ->where('id', '=', $sku_id)
            ->execute()
            ->current();
        if (!$sku) {
            return false;
        }

        $data = array();
        if ($sku['period_time_id']) {
            $period_time = DB::select('start', 'end')
                ->from('spot_period_time')
                ->where('id', '=', $sku['period_time_id'])
                ->execute()
                ->current();
            if ($period_time) {
                $period_time['des']  = $period_time['start'] . '-' . $period_time['end'];
                $data['period_time'] = $period_time;
            }
        }
        return $data;
    }

    /**
     * 判断门票是否有规格
     * @param $ticket_id
     * @return bool
     */
    public static function ticket_has_sku($ticket_id)
    {
        return DB::select()
            ->from('spot_ticket_sku')
            ->where('ticket_id', '=', $ticket_id)
            ->execute()
            ->valid();
    }
}